<template>
  <div class="chat-management">
    <div class="header">
      <h2>채팅방 관리</h2>
      <el-button type="primary" @click="openCreate">채팅방 생성</el-button>
    </div>

    <div class="toolbar">
      <el-input v-model="search" placeholder="제목으로 검색" style="width: 260px" @keyup.enter="fetchRooms" />
      <el-button @click="fetchRooms">검색</el-button>
    </div>

    <el-table :data="rooms" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="제목" min-width="260" />
      <el-table-column prop="status" label="상태" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="authStore.isAdmin" label="생성자" width="150">
        <template #default="{ row }">
          <span v-if="row.creator">{{ row.creator.nickname || row.creator.name || row.creator.loginId }}</span>
          <span v-else class="text-gray-400">시스템</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="생성 시간" width="180">
        <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="작업" width="240" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">편집</el-button>
          <el-button size="small" @click="openMessages(row)">정보 관리</el-button>
          <el-button type="danger" size="small" :loading="row.deleting" @click="removeRoom(row)">삭제</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="limit"
        :page-sizes="[10,20,50,100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchRooms"
        @current-change="fetchRooms"
      />
    </div>

    <!-- 생성/편집 -->
    <el-dialog v-model="showDialog" :title="editing ? '채팅방 편집' : '채팅방 생성'" width="520px">
      <el-form :model="form" label-width="90px">
        <el-form-item label="제목" required>
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="표시 이름">
          <el-input v-model="form.displayName" placeholder="목록에서 우선 표시" />
        </el-form-item>
        <el-form-item label="커버">
          <el-upload
            class="uploader"
            :action="`${API_BASE_URL}/api/admin/uploads/cover`"
            name="cover-upload"
            :with-credentials="true"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
          >
            <img v-if="form.coverUrl" :src="`${API_BASE_URL}${form.coverUrl}`" class="cover" />
            <el-button v-else type="primary">이미지 선택</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="소개">
          <el-input type="textarea" rows="4" v-model="form.description" />
        </el-form-item>
        <el-form-item label="성별">
          <el-select v-model="form.gender" style="width:100%">
            <el-option label="알 수 없음" value="unknown" />
            <el-option label="남성" value="male" />
            <el-option label="여성" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item label="활성화">
          <el-switch v-model="form.active" />
        </el-form-item>
        <el-form-item label="방 정원">
          <el-input-number v-model="form.capacity" :min="1" />
        </el-form-item>
        <el-form-item label="입장 비밀번호">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="비밀번호를 설정하지 않으면 누구나 입장 가능"
            show-password
            clearable
          />
          <div class="form-tip">비밀번호를 설정하면 일반 사용자는 비밀번호를 입력해야 입장할 수 있습니다. 관리자와 파트너는 비밀번호 없이 입장 가능합니다.</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog=false">취소</el-button>
        <el-button type="primary" :loading="saving" :disabled="!form.title" @click="save">{{ editing ? '저장' : '생성' }}</el-button>
      </template>
    </el-dialog>

    <!-- 미리 설정된 메시지 관리 -->
    <el-dialog v-model="showPresets" title="미리 설정된 메시지" width="720px">
      <div class="presets-header">
        <el-button type="primary" size="small" @click="addPreset">메시지 추가</el-button>
      </div>
      <el-table :data="presets" style="width: 100%">
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="content" label="内容" min-width="360">
          <template #default="{ row }">
            <el-input v-if="row.editing" v-model="row.content" @keyup.enter="savePreset(row)" @blur="savePreset(row)" />
            <span v-else>{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="启用" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.isActive" @change="savePreset(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button v-if="!row.editing" size="small" @click="row.editing=true">编辑</el-button>
            <el-button v-else size="small" type="primary" @click="savePreset(row)">保存</el-button>
            <el-button type="danger" size="small" @click="removePreset(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 消息管理弹窗 -->
    <el-dialog v-model="showMessages" title="消息管理" width="1000px">
      <div class="messages-header">
        <el-input v-model="messageSearch" placeholder="搜索消息内容" style="width: 260px" @keyup.enter="fetchMessages" />
        <el-button @click="fetchMessages">搜索</el-button>
        <el-button type="primary" @click="addMessage">添加消息</el-button>
      </div>
      <el-table :data="messages" v-loading="messagesLoading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="消息内容" min-width="300">
          <template #default="{ row }">
            <el-input v-if="row.editing" v-model="row.content" type="textarea" :rows="2" @keyup.enter="saveMessage(row)" @blur="saveMessage(row)" />
            <span v-else>{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发送者" width="150">
          <template #default="{ row }">
            <span v-if="row.isSystem" class="text-blue-600">系统消息</span>
            <span v-else-if="row.user">{{ row.user.nickname || row.user.name || row.user.loginId }}</span>
            <span v-else class="text-gray-400">未知用户</span>
          </template>
        </el-table-column>
        <el-table-column prop="isSystem" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isSystem ? 'info' : 'success'">{{ row.isSystem ? '系统' : '用户' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button v-if="!row.editing" size="small" @click="row.editing=true">编辑</el-button>
            <el-button v-else size="small" type="primary" @click="saveMessage(row)">保存</el-button>
            <el-button type="danger" size="small" @click="removeMessage(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="messages-pagination">
        <el-pagination
          v-model:current-page="messagePage"
          v-model:page-size="messageLimit"
          :page-sizes="[10,20,50,100]"
          :total="messageTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchMessages"
          @current-change="fetchMessages"
        />
      </div>
    </el-dialog>

    <!-- 添加消息弹窗 -->
    <el-dialog v-model="showAddMessage" title="添加消息" width="520px">
      <el-form :model="messageForm" label-width="90px">
        <el-form-item label="消息内容" required>
          <el-input v-model="messageForm.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-radio-group v-model="messageForm.isSystem">
            <el-radio :label="false">用户消息</el-radio>
            <el-radio :label="true">系统消息</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddMessage=false">取消</el-button>
        <el-button type="primary" :loading="savingMessage" :disabled="!messageForm.content" @click="saveNewMessage">添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

const authStore = useAuthStore()
const router = useRouter()

const loading = ref(false)
const rooms = ref<any[]>([])
const page = ref(1)
const limit = ref(20)
const total = ref(0)
const search = ref('')

const showDialog = ref(false)
const editing = ref(false)
const form = ref({ title: '', displayName: '', coverUrl: '', description: '', gender: 'unknown', capacity: 1, status: 'active', active: true, password: '' })
const saving = ref(false)
let currentRoomId: string | null = null

const showPresets = ref(false)
const presets = ref<any[]>([])

// 消息管理相关变量
const showMessages = ref(false)
const messages = ref<any[]>([])
const messagesLoading = ref(false)
const messagePage = ref(1)
const messageLimit = ref(20)
const messageTotal = ref(0)
const messageSearch = ref('')

// 添加消息相关变量
const showAddMessage = ref(false)
const messageForm = ref({ content: '', isSystem: false })
const savingMessage = ref(false)

const handleCoverSuccess = (res: any) => {
  if (res?.coverUrl) form.value.coverUrl = res.coverUrl
}

const fetchRooms = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/admin/chat-rooms', { params: { page: page.value, limit: limit.value, search: search.value } })
    rooms.value = res.data.rooms
    total.value = res.data.total
  } catch (e) {
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

const openCreate = () => { editing.value = false; form.value = { title: '', displayName: '', coverUrl: '', description: '', gender: 'unknown', capacity: 1, status: 'active', active: true, password: '' }; showDialog.value = true }
const openEdit = (row: any) => { editing.value = true; currentRoomId = String(row.id); form.value = { title: row.title || '', displayName: row.displayName || '', coverUrl: row.coverUrl || '', description: row.description || '', gender: row.gender || 'unknown', capacity: row.capacity || 1, status: row.status, active: row.status === 'active', password: row.password || '' }; showDialog.value = true }

const save = async () => {
  saving.value = true
  try {
    const payload = { ...form.value, status: form.value.active ? 'active' : 'archived' }
    if (editing.value && currentRoomId) {
      await request.put(`/api/admin/chat-rooms/${currentRoomId}`, payload)
      ElMessage.success('保存成功')
    } else {
      await request.post('/api/admin/chat-rooms', payload)
      ElMessage.success('创建成功')
    }
    showDialog.value = false
    await fetchRooms()
  } catch (e) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const removeRoom = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定删除该聊天室？', '确认', { type: 'warning' })
    row.deleting = true
    await request.delete(`/api/admin/chat-rooms/${row.id}`)
    ElMessage.success('删除成功')
    await fetchRooms()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('删除失败')
  } finally {
    row.deleting = false
  }
}

const openPresets = async (row: any) => {
  currentRoomId = String(row.id)
  try {
    const res = await request.get(`/api/admin/chat-rooms/${currentRoomId}/presets`)
    presets.value = res.data.presets.map((p: any) => ({ ...p, editing: false }))
    showPresets.value = true
  } catch (e) {
    ElMessage.error('获取预设失败')
  }
}

const addPreset = () => { presets.value.push({ id: null, sortOrder: presets.value.length, content: '新消息', isActive: true, editing: true }) }

const savePreset = async (p: any) => {
  try {
    if (p.id) {
      await request.put(`/api/admin/chat-rooms/${currentRoomId}/presets/${p.id}`, { content: p.content, sortOrder: p.sortOrder, isActive: p.isActive })
    } else {
      const r = await request.post(`/api/admin/chat-rooms/${currentRoomId}/presets`, { content: p.content, sortOrder: p.sortOrder })
      p.id = r.data.id
    }
    p.editing = false
    ElMessage.success('已保存')
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const removePreset = async (p: any) => {
  try {
    await ElMessageBox.confirm('确定删除这条预设？', '确认', { type: 'warning' })
    if (p.id) await request.delete(`/api/admin/chat-rooms/${currentRoomId}/presets/${p.id}`)
    const idx = presets.value.indexOf(p)
    presets.value.splice(idx, 1)
    ElMessage.success('已删除')
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('删除失败')
  }
}

// 消息管理相关函数
const openMessages = (row: any) => {
  // 跳转到新的聊天室界面
  router.push(`/chat-rooms/${row.id}/view`)
}

const fetchMessages = async () => {
  if (!currentRoomId) return
  messagesLoading.value = true
  try {
    const res = await request.get(`/api/admin/chat-rooms/${currentRoomId}/messages`, {
      params: { page: messagePage.value, limit: messageLimit.value, search: messageSearch.value }
    })
    messages.value = res.data.messages.map((m: any) => ({ ...m, editing: false }))
    messageTotal.value = res.data.total
  } catch (e) {
    ElMessage.error('获取消息失败')
  } finally {
    messagesLoading.value = false
  }
}

const addMessage = () => {
  messageForm.value = { content: '', isSystem: false }
  showAddMessage.value = true
}

const saveNewMessage = async () => {
  if (!currentRoomId || !messageForm.value.content) return
  savingMessage.value = true
  try {
    await request.post(`/api/admin/chat-rooms/${currentRoomId}/messages`, messageForm.value)
    ElMessage.success('消息添加成功')
    showAddMessage.value = false
    await fetchMessages()
  } catch (e) {
    ElMessage.error('添加消息失败')
  } finally {
    savingMessage.value = false
  }
}

const saveMessage = async (message: any) => {
  if (!currentRoomId || !message.content) return
  try {
    await request.put(`/api/admin/chat-rooms/${currentRoomId}/messages/${message.id}`, {
      content: message.content
    })
    message.editing = false
    ElMessage.success('消息更新成功')
  } catch (e) {
    ElMessage.error('更新消息失败')
  }
}

const removeMessage = async (message: any) => {
  if (!currentRoomId) return
  try {
    await ElMessageBox.confirm('确定删除这条消息？', '确认', { type: 'warning' })
    await request.delete(`/api/admin/chat-rooms/${currentRoomId}/messages/${message.id}`)
    ElMessage.success('消息删除成功')
    await fetchMessages()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('删除消息失败')
  }
}

const formatDate = (s: string) => new Date(s).toLocaleString('zh-CN')

onMounted(fetchRooms)
</script>

<style scoped>
.chat-management{padding:20px}
.header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}
.toolbar{display:flex;gap:8px;margin-bottom:12px}
.pagination{margin-top:16px;text-align:right}
.presets-header{margin-bottom:12px}
.cover{width:120px;height:120px;object-fit:cover;border-radius:6px;border:1px solid #ddd}
.messages-header{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.messages-pagination{margin-top:16px;text-align:right}
.form-tip{font-size:12px;color:#909399;margin-top:4px;line-height:1.4}
</style>

